/*easyui样式初始化*/
$.fn.tabs.defaults.tabHeight = 36; //tab标签条高度
$.fn.linkbutton.defaults.height = 36; //按钮高度
$.fn.switchbutton.defaults.height = 36; //按钮高度
$.fn.menu.defaults.itemHeight = 32; //menu高度

$.fn.validatebox.defaults.height = 36;
$.fn.textbox.defaults.height = 36;
$.fn.textbox.defaults.iconWidth = 28;
$.fn.datebox.defaults.height = 36;
$.fn.numberspinner.defaults.height = 36;
$.fn.timespinner.defaults.height = 36;
$.fn.numberbox.defaults.height = 36;

$.fn.combobox.defaults.height = 36;
$.fn.combobox.defaults.method = 'GET';
$.fn.combobox.defaults.loadFilter = function (data) {
	if (data && data.code && data.code <= 0) {
		if (data.code == 0) {
			$.messager.alert('错误信息', data.message, 'error');
		} else if (data.code == -1 || data.code == -3) {
			window.location.href = 'login.html';
		} else if (data.code == -2) {
			showMessage('权限不足...');
		}
		return [];
	}
	return (data instanceof Array) ? data : data.datas;
}

$.fn.combotree.defaults.height = 36;
$.fn.combogrid.defaults.height = 36;
$.fn.passwordbox.defaults.height = 36;
$.fn.filebox.defaults.height = 36;

$.fn.menu.defaults.noline = true
$.fn.progressbar.defaults.height = 22; //进度条

$.fn.datagrid.defaults.pagination = true;
$.fn.datagrid.defaults.striped = true;
$.fn.datagrid.defaults.fitColumns = true;
$.fn.datagrid.defaults.pageSize = 20;
$.fn.datagrid.defaults.pageList = [20, 50, 100, 200, 500];
$.fn.datagrid.defaults.method = 'GET';
$.fn.datagrid.defaults.loadFilter = function (data) {
	if (data && data.code && data.code <= 0) {
		if (data.code == 0) {
			$.messager.alert('错误信息', data.message, 'error');
		} else if (data.code == -1 || data.code == -3) {
			window.location.href = 'login.html';
		} else if (data.code == -2) {
			showMessage('权限不足...');
		}
		return {
			total: 0,
			rows: []
		};
	} else {
		if (data instanceof Array) return {
			total: data.length,
			rows: data
		};
		if (data.datas instanceof Array) return {
			total: data.datas.length,
			rows: data.datas
		};
		if (!data.datas.totalElements) return {
			total: 0,
			rows: []
		};
		return {
			total: data.datas.totalElements,
			rows: data.datas.content
		}
	}
}

$.fn.treegrid.defaults.pagination = false;
$.fn.treegrid.defaults.striped = true;
$.fn.treegrid.defaults.fitColumns = true;
$.fn.treegrid.defaults.method = 'GET';
$.fn.treegrid.defaults.loadFilter = function (data) {
	if (data && data.code && data.code <= 0) {
		if (data.code == 0) {
			$.messager.alert('错误信息', data.message, 'error');
		} else if (data.code == -1 || data.code == -3) {
			window.location.href = 'login.html';
		} else if (data.code == -2) {
			showMessage('权限不足...');
		}
		return {
			total: 0,
			rows: []
		};
	} else {
		if (data instanceof Array) return {
			total: data.length,
			rows: data
		};
		if (data.datas instanceof Array) return {
			total: data.datas.length,
			rows: data.datas
		};
		if (!data.datas.totalElements) return {
			total: 0,
			rows: []
		};
		return {
			total: data.datas.totalElements,
			rows: data.datas.content
		}
	}
}

$.fn.window.defaults.collapsible = false;


function Map() {
	this.obj = {};
	this.count = 0;
}
Map.prototype.put = function (key, value) {
	var oldValue = this.obj[key];
	if (oldValue == undefined) {
		this.count++;
	}
	this.obj[key] = value;
}
Map.prototype.get = function (key) {
	return this.obj[key];
}
Map.prototype.remove = function (key) {
	var oldValue = this.obj[key];
	if (oldValue != undefined) {
		this.count--;
		delete this.obj[key];
	}
}
Map.prototype.size = function () {
	return this.count;
}

var commonConfig = {
	shopUrlMap: null,
	mgUrlMap: null,
	shopUrlPrefix: function () {
		if (commonConfig.shopUrlMap == null) commonConfig.initShopUrlMap();
		return commonConfig.shopUrlMap.get(window.location.hostname);
	},
	mgUrlPrefix: function () {
		if (commonConfig.mgUrlMap == null) commonConfig.initMgUrlMap();
		return commonConfig.mgUrlMap.get(window.location.hostname);
	},
	initShopUrlMap: function () {
		commonConfig.shopUrlMap = new Map();
		commonConfig.shopUrlMap.put('127.0.0.1', 'http://localhost:9020');
		commonConfig.shopUrlMap.put('47.236.181.95', 'http://47.236.181.95:9020');
		commonConfig.shopUrlMap.put('mn.buyfunshop.com', 'http://fr.buyfunshop.com');
	},
	initMgUrlMap: function () {
		commonConfig.mgUrlMap = new Map();
		commonConfig.mgUrlMap.put('127.0.0.1', 'http://localhost:9021');
		commonConfig.mgUrlMap.put('47.236.181.95', 'http://47.236.181.95:9021');
		commonConfig.mgUrlMap.put('mn.buyfunshop.com', 'http://mn.ds.buyfunshop.com');
	}
}

$(function () {
	var _token = localStorage.getItem('token');
	if (window.location.pathname.indexOf('login.html') == -1 && !_token || _token == '') {
		window.location.href = 'login.html';
	}

	$.ajaxSetup({
		headers: {
			Authorization: 'Bearer ' + localStorage.getItem('token')
		}
	});
});

/**
 * 表单序列化为JSON
 * @param {Object} $
 */
$.fn.serializeJson = function () {
	var serializeObj = {};
	var array = this.serializeArray();
	$(array).each(function () {
		if (serializeObj[this.name]) {
			if ($.isArray(serializeObj[this.name])) {
				serializeObj[this.name].push(this.value);
			} else {
				serializeObj[this.name] = [serializeObj[this.name], this.value];
			}
		} else {
			serializeObj[this.name] = this.value;
		}
	});
	return serializeObj;
};

Date.prototype.Format = function (fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份   
		"d+": this.getDate(), //日   
		"h+": this.getHours(), //小时   
		"m+": this.getMinutes(), //分   
		"s+": this.getSeconds(), //秒   
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度   
		"S": this.getMilliseconds() //毫秒   
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

/**
 * 请求封装
 */
var requestBodyServer = function (_url, _method, _data) {
	var token = localStorage.getItem('token') // 登录凭证
	return new Promise((resolve, reject) => {
		$.ajax({
			type: _method,
			headers: {
				Authorization: 'Bearer ' + token
			},
			url: _url,
			data: typeof (_data) == 'string' ? _data : JSON.stringify(_data),
			dataType: 'json',
			contentType: 'application/json',
			beforeSend: function(){
				tools.showLoading()
			},
			success: function (response) {
				if (response.code == 0) {
					$.messager.alert('错误信息', response.message, 'error');
				} else if (response.code == -1 || response.code == -3) {
					window.location.href = 'login.html';
				} else if (response.code == -2) {
					showMessage('权限不足...');
				} else {
					resolve(response);
				}
				tools.hideLoading()
			},
				error: function (error) {
				reject(error)
				tools.hideLoading()
			}
		})
	})
}
var requestServer = function (_url, _method, _data) {
	var token = localStorage.getItem('token') // 登录凭证
	return new Promise((resolve, reject) => {
		$.ajax({
			type: _method,
			headers: {
				Authorization: 'Bearer ' + token
			},
			url: _url,
			data: _data,
			dataType: 'json',
			contentType: 'application/json',
			beforeSend: function(){
				tools.showLoading()
			},
			success: function (response) {
				if (response.code == 0) {
					$.messager.alert('错误信息', response.message, 'error');
				} else if (response.code == -1 || response.code == -3) {
					window.location.href = 'login.html';
				} else if (response.code == -2) {
					showMessage('权限不足...');
				} else {
					resolve(response);
				}
				tools.hideLoading()
			},
			error: function (error) {
				reject(error)
				tools.hideLoading()
			}
		})
	})
}

var showMessage = function (msg) {
	$.messager.show({
		height: 42,
		timeout: 2000,
		showSpeed: 200,
		msg: msg,
		style: {
			'right': '',
			'top': document.body.scrollTop + document.documentElement.scrollTop + 20,
			'bottom': '',
			'z-index': 999,
			'box-shadow': '0 1px 6px rgba(0,0,0,.2)',
			'background': '#ff4142',
			'color': '#FFF',
			'border': 'none',
		}
	});
}
var FormatDate = function (dateValue) {
	return new Date(dateValue).Format('yyyy-MM-dd hh:mm:ss');
}

var exportExcel = function (href, params) {
	requestServer(href, 'GET', params).then((response) => {
		if (data.code == 0) {
			$.messager.alert('错误信息', data.message, 'error');
		} else if (data.code == -1 || data.code == -3) {
			window.location.href = 'login.html';
		} else if (data.code == -2) {
			showMessage('权限不足...');
		}
	}).catch((error) => {
		exportFile(error.responseText);
	});
}

var exportFile = function (url) {
    var link = ('http://47.241.217.12:8013' + url).replace('data/', '');
    window.open(link);
}

var timestamp = function (data) {
	if (data) {
		var now = moment(data, 'YYYY-MM-DD HH:mm').valueOf().toString().substring(0, 10)
		return now
	} else {
		return ''
	}
}

var globalDaterangepickerOptions = {
	timePicker: true,
	startDate: moment().startOf('day').subtract(2, 'days'),
	endDate: moment().endOf('day'),
	timePickerIncrement: 30,
	timePicker24Hour: true,
	locale: {
		format: 'YYYY-MM-DD HH:mm:ss',
		applyLabel: '确定',
		cancelLabel: '取消',
		customRangeLabel: '自定义'
	},
	ranges: {
		'今天': [moment().startOf('day'), moment().endOf('day')],
		'昨天': [moment().startOf('day').subtract(1, 'days'), moment().endOf('day').subtract(1, 'days')],
		'过去7天': [moment().startOf('day').subtract(7, 'days'), moment().endOf('day').subtract(1, 'days')],
		'过去30天': [moment().startOf('day').subtract(30, 'days'), moment().endOf('day').subtract(1, 'days')],
		'本月': [moment().startOf('month'), moment().endOf('month')],
		'上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
	}
}
var monitorlDaterangepickerOptions = {
	timePicker: false,
	startDate: moment().startOf('day').subtract(2, 'days'),
	endDate: moment().endOf('day'),
	locale: {
		format: 'YYYY-MM-DD',
		applyLabel: '确定',
		cancelLabel: '取消',
		customRangeLabel: '自定义'
	},
	ranges: {
		'今天': [moment().startOf('day'), moment().endOf('day')],
		'昨天': [moment().startOf('day').subtract(1, 'days'), moment().endOf('day').subtract(1, 'days')],
		'过去7天': [moment().startOf('day').subtract(7, 'days'), moment().endOf('day').subtract(1, 'days')],
		'过去30天': [moment().startOf('day').subtract(30, 'days'), moment().endOf('day').subtract(1, 'days')],
		'本月': [moment().startOf('month'), moment().endOf('month')],
		'上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
	}
}

var showErrorMsgs = function (_data, _columns) {
	$('#error-message-window').remove();
	$('<div id="error-message-window" style="width:800px"></div>').appendTo('body');
	$('#error-message-window').window({
		width: 1000,
		height: 600,
		title: '信息',
		modal: true,
		minimizable: false,
		maximizable: false,
		content: '<table id="error-message-datagrid"></table>',
		onClose: function () {
			$('#error-message-window').remove();
		}
	});

	$('#error-message-datagrid').datagrid({
		fit: true,
		pagination: false,
		rowStyler: function () {
			return "height:38px";
		},
		data: _data,
		columns: _columns
	});
}

var tools = {
	shuffle: function(arr) {
		// 数组乱序
		let len = arr.length;
		while (len) {
		  let i = (Math.random() * len--) >> 0;    // 交换位置
		  let temp = arr[len];
		  arr[len] = arr[i];
		  arr[i] = temp;
		}
		return arr;
	},
	copyToClipboard: function (text) {
		var element = $("<textarea>" + text + "</textarea>");
		$("body").append(element);
		element[0].select();
		document.execCommand("Copy");
		element.remove();
		showMessage('复制成功···')
	},
	testLink: function(val){
		return /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/.test(val)
	},
	showLoading: function(){
		if($('#loading_global').length < 1){
			$('body').append('<div id="loading_global"><svg viewBox="0 0 120 120" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g id="circle" class="g-circles g-circles--v3"><circle id="12" transform="translate(35, 16.698730) rotate(-30) translate(-35, -16.698730) " cx="35" cy="16.6987298" r="10"></circle><circle id="11" transform="translate(16.698730, 35) rotate(-60) translate(-16.698730, -35) " cx="16.6987298" cy="35" r="10"></circle><circle id="10" transform="translate(10, 60) rotate(-90) translate(-10, -60) " cx="10" cy="60" r="10"></circle><circle id="9" transform="translate(16.698730, 85) rotate(-120) translate(-16.698730, -85) " cx="16.6987298" cy="85" r="10"></circle><circle id="8" transform="translate(35, 103.301270) rotate(-150) translate(-35, -103.301270) " cx="35" cy="103.30127" r="10"></circle><circle id="7" cx="60" cy="110" r="10"></circle><circle id="6" transform="translate(85, 103.301270) rotate(-30) translate(-85, -103.301270) " cx="85" cy="103.30127" r="10"></circle><circle id="5" transform="translate(103.301270, 85) rotate(-60) translate(-103.301270, -85) " cx="103.30127" cy="85" r="10"></circle><circle id="4" transform="translate(110, 60) rotate(-90) translate(-110, -60) " cx="110" cy="60" r="10"></circle><circle id="3" transform="translate(103.301270, 35) rotate(-120) translate(-103.301270, -35) " cx="103.30127" cy="35" r="10"></circle><circle id="2" transform="translate(85, 16.698730) rotate(-150) translate(-85, -16.698730) " cx="85" cy="16.6987298" r="10"></circle><circle id="1" cx="60" cy="10" r="10"></circle></g></svg></div>')
		}
		$('#loading_global').show().on('click', function(){return false})
	},
	hideLoading: function(){
		$('#loading_global').hide()
	},
	printProductBarcode: function(product_parame){
		if(!product_parame || !product_parame.product_id || !product_parame.product_sku_name || !product_parame.product_title || !product_parame.product_sku_barcode){
			showMessage('条码参数有误···');	
			return
		}
		tools.showLoading()
		// 加载js
		Promise.all([
			tools.loadJS("dists/super/js/JsBarcode.all.min.js", "js_jsbarcode_min"), 
			tools.loadJS("dists/super/js/jQuery.print.min.js", "js_jqprint_min")
		]).then(() => {
			var sku_name = product_parame.product_sku_name,
				product_title = product_parame.product_title;
			var html = '<form method="post" action="#" id="printBoxForm"  style="padding:4px; display: block; margin: 0 auto;">'+
						'<div style="font-size:16px;text-align:center;font-weight:700;letter-spacing: 2px">' + product_parame.product_sku_barcode + '</div>'+
						'<img id="imgcode" style="display:block;margin: 4px auto 0;height: 40px; width:90%"/>'+
						'<div style="margin:10px 0 0 0;font-size:12px;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;">' + product_title + '</div>'+
						'<div style="margin:4px 0 0 0;font-weight:700;font-size:13px;line-height: 16px;overflow:hidden; text-overflow:ellipsis;display:-webkit-box; -webkit-box-orient:vertical;-webkit-line-clamp:2; ">' + sku_name + '</div>'+
						'</form>';
			if($('#print_product_barcode_box').length == 0){
				$('body').append('<div id="print_product_barcode_box" style="display:none"></div>');
			}
			$('#print_product_barcode_box').html(html);
			JsBarcode("#imgcode", product_parame.product_sku_barcode, {
				width: 3,
				margin: 3,
				fontSize: 0
			});
			$('#printBoxForm').print();
			tools.hideLoading()
        }).catch((err)=>{
			showMessage('加载失败，请联系管理员');
			tools.hideLoading()
		})
	},
	valueBypass: function(value, max_length){
        return value.length <= max_length ? value : (value.slice(0, max_length) + '···');
	},
	loadJS: function(src, id){
		var script = null
		if($('#' + id).length == 0){
			script = document.createElement('script');
			var head = document.getElementsByTagName('head')[0];
			script.src = src;
			script.type = "text/javascript";
			script.id = id;
			head.appendChild(script);
		}
		return new Promise(function(resolve, reject){        //做一些异步操作
			if(script != null){
				script.onload = script.onreadystatechange = function(){
					if(!script.readyState || /loaded|complete/.test(script.readyState)){
						resolve();
					}else{
						reject();
					}
				}
			}else{
				resolve();
			}
		});
	},
	clearLocalStorage: function(){
		for(var i in localStorage){
			localStorage.removeItem(i)
		}
	},
	bigImg: function(target){
		var _offset = $(target).offset();
		var _src = $(target).attr('src');
		$(`<img class="bigImg" src="${_src}" />`).appendTo('body');
		$('.bigImg').css({top: _offset.top - 350, left: _offset.left + 60});
	},
	normalImg: function(){
		$('.bigImg').remove();
	}
};

(function ($) {
	$.fn.serializeJson = function () {
		var serializeObj = {};
		var array = this.serializeArray();
		var str = this.serialize();
		$(array).each(function () {
			if (serializeObj[this.name]) {
				if ($.isArray(serializeObj[this.name]) && this.value != "") {
					serializeObj[this.name].push(this.value);
				} else {
					if (this.value != "") {
						serializeObj[this.name] = [serializeObj[this.name], this.value];
					}
				}
			} else {
				if (this.value != "") {
					serializeObj[this.name] = this.value;
				}
			}
		});
		return serializeObj;
	};
})(jQuery);